<template>
  <el-dialog v-model="state.changePasswordDialog" title="修改密码" width="400px">
    <el-form class="login-form" :label-position="labelPosition" :rules="rules">
      <el-form-item label="请输入您的旧密码" prop="oldPassword">
        <el-input v-model="passwordData.oldPassword" placeholder="请输入您的旧密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="再次输入您的新密码" prop="newPassword">
        <el-input v-model="passwordData.newPassword" placeholder="再次输入您的新密码" show-password></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <span class="dialog-footer">
          <el-button @click="state.changePasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="changeUserPassword">确定</el-button>
        </span>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { changePassword } from '@/api/userInfo'

defineOptions({
  name: ''
})

const state = reactive({
  changePasswordDialog: false,
})

interface PasswordData {
  oldPassword: string;
  newPassword: string;
}

const passwordData: PasswordData = reactive({
  oldPassword: '',
  newPassword: '',
})

const labelPosition = ref('top')

const rules = reactive({
  oldPassword: [{ required: true, message: '请输入您的新密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请再次输入您的新密码', trigger: 'blur' }],
})

const changeUserPassword = async () => {
  const id = localStorage.getItem('id')!
  if(passwordData.oldPassword && passwordData.newPassword){
    await changePassword({ id, ...passwordData })
    state.changePasswordDialog = false
  }
}

const open = () => {
  state.changePasswordDialog = true
}

defineExpose({
  open
})
</script>